package assignment1;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

/**
 * 
 * @author Kha Nguyen - 598240
 *
 */
public class ReadShakespeareTextTask implements Runnable {

    private final String fileName;

    private final List<String> textContainer;

    public ReadShakespeareTextTask(String fileName, List<String> textContainer) {
        super();
        this.fileName = fileName;
        this.textContainer = textContainer;
    }

    @Override
    public void run() {
        Scanner reader = null;
        try {
            final File fileToProcess = new File(fileName);
            reader = new Scanner(fileToProcess);

            while (reader.hasNextLine()) {
                final String line = reader.nextLine().toLowerCase().replaceAll("[^a-zA-Z0-9]", " ");

                for (String token : line.split(" ")) {
                    if (token.isEmpty()) {
                        continue;
                    }

                    if (!token.matches("^[a-zA-Z0-9]+$")) {
                        throw new RuntimeException(token);
                    }
                    textContainer.add(token);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
}
